import { LEANCLOUD_CONFIG, ACCOUNT_FIELDS } from "../config/leancloud.js";

// LeanCloud API封装类
class LeanCloudAPI {
	constructor() {
		this.baseURL = LEANCLOUD_CONFIG.serverURL;
		this.appId = LEANCLOUD_CONFIG.appId;
		this.appKey = LEANCLOUD_CONFIG.appKey;
		this.className = "Account"; // LeanCloud中的类名
	}

	// 获取请求头
	getHeaders() {
		return {
			"Content-Type": "application/json",
			"X-LC-Id": this.appId,
			"X-LC-Key": this.appKey,
		};
	}

	// 构建URL
	buildURL(endpoint) {
		return `${this.baseURL}/1.1${endpoint}`;
	}

	// 处理响应
	async handleResponse(response) {
		const data = await response.json();

		if (!response.ok) {
			throw new Error(data.error || `HTTP error! status: ${response.status}`);
		}

		return data;
	}

	// 用户注册
	async register(userData) {
		try {
			const response = await fetch(this.buildURL("/classes/Account"), {
				method: "POST",
				headers: this.getHeaders(),
				body: JSON.stringify({
					[ACCOUNT_FIELDS.USERNAME]: userData.username,
					[ACCOUNT_FIELDS.PASSWORD]: userData.password,
					[ACCOUNT_FIELDS.IS_ACTIVE]: true,
				}),
			});

			const data = await this.handleResponse(response);

			return {
				success: true,
				data: {
					objectId: data.objectId,
					createdAt: data.createdAt,
					...userData,
				},
			};
		} catch (error) {
			console.error("注册失败:", error);
			return {
				success: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 用户登录
	async login(username, password) {
		try {
			// 查询用户
			const response = await fetch(
				this.buildURL(
					`/classes/Account?where=${encodeURIComponent(
						JSON.stringify({
							[ACCOUNT_FIELDS.USERNAME]: username,
							[ACCOUNT_FIELDS.PASSWORD]: password,
							[ACCOUNT_FIELDS.IS_ACTIVE]: true,
						})
					)}`
				),
				{
					method: "GET",
					headers: this.getHeaders(),
				}
			);

			const data = await this.handleResponse(response);

			if (data.results && data.results.length > 0) {
				const user = data.results[0];

				// 更新最后登录时间
				await this.updateLastLogin(user.objectId);

				return {
					success: true,
					data: {
						objectId: user.objectId,
						username: user[ACCOUNT_FIELDS.USERNAME],
						email: user[ACCOUNT_FIELDS.EMAIL],
						phone: user[ACCOUNT_FIELDS.PHONE],
						gender: user[ACCOUNT_FIELDS.GENDER],
						createdAt: user[ACCOUNT_FIELDS.CREATED_AT],
						lastLogin: user[ACCOUNT_FIELDS.LAST_LOGIN],
					},
				};
			} else {
				return {
					success: false,
					error: "用户名或密码错误",
				};
			}
		} catch (error) {
			console.error("登录失败:", error);
			return {
				success: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 更新最后登录时间
	async updateLastLogin(objectId) {
		try {
			await fetch(this.buildURL(`/classes/Account/${objectId}`), {
				method: "PUT",
				headers: this.getHeaders(),
				body: JSON.stringify({
					[ACCOUNT_FIELDS.LAST_LOGIN]: {
						__type: "Date",
						iso: new Date().toISOString()
					}
				}),
			});
		} catch (error) {
			console.error("更新最后登录时间失败:", error);
		}
	}

	// 检查用户名是否已存在
	async checkUsernameExists(username) {
		try {
			const response = await fetch(
				this.buildURL(
					`/classes/Account?where=${encodeURIComponent(
						JSON.stringify({
							[ACCOUNT_FIELDS.USERNAME]: username,
						})
					)}`
				),
				{
					method: "GET",
					headers: this.getHeaders(),
				}
			);

			const data = await this.handleResponse(response);
			return {
				exists: data.results && data.results.length > 0,
				count: data.results ? data.results.length : 0,
			};
		} catch (error) {
			console.error("检查用户名失败:", error);
			return {
				exists: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 检查邮箱是否已存在
	async checkEmailExists(email) {
		try {
			const response = await fetch(
				this.buildURL(
					`/classes/Account?where=${encodeURIComponent(
						JSON.stringify({
							[ACCOUNT_FIELDS.EMAIL]: email,
						})
					)}`
				),
				{
					method: "GET",
					headers: this.getHeaders(),
				}
			);

			const data = await this.handleResponse(response);
			return {
				exists: data.results && data.results.length > 0,
				count: data.results ? data.results.length : 0,
			};
		} catch (error) {
			console.error("检查邮箱失败:", error);
			return {
				exists: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 检查手机号是否已存在
	async checkPhoneExists(phone) {
		try {
			const response = await fetch(
				this.buildURL(
					`/classes/Account?where=${encodeURIComponent(
						JSON.stringify({
							[ACCOUNT_FIELDS.PHONE]: phone,
						})
					)}`
				),
				{
					method: "GET",
					headers: this.getHeaders(),
				}
			);

			const data = await this.handleResponse(response);
			return {
				exists: data.results && data.results.length > 0,
				count: data.results ? data.results.length : 0,
			};
		} catch (error) {
			console.error("检查手机号失败:", error);
			return {
				exists: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 获取用户信息
	async getUserInfo(objectId) {
		try {
			const response = await fetch(this.buildURL(`/classes/Account/${objectId}`), {
				method: "GET",
				headers: this.getHeaders(),
			});

			const data = await this.handleResponse(response);

			return {
				success: true,
				data: {
					objectId: data.objectId,
					username: data[ACCOUNT_FIELDS.USERNAME],
					email: data[ACCOUNT_FIELDS.EMAIL],
					phone: data[ACCOUNT_FIELDS.PHONE],
					gender: data[ACCOUNT_FIELDS.GENDER],
					avatar: data[ACCOUNT_FIELDS.AVATAR],
					isActive: data[ACCOUNT_FIELDS.IS_ACTIVE],
					lastLogin: data[ACCOUNT_FIELDS.LAST_LOGIN],
					createdAt: data[ACCOUNT_FIELDS.CREATED_AT],
					updatedAt: data[ACCOUNT_FIELDS.UPDATED_AT],
				},
			};
		} catch (error) {
			console.error("获取用户信息失败:", error);
			return {
				success: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 更新用户信息
	async updateUserInfo(objectId, updateData) {
		try {
			const response = await fetch(this.buildURL(`/classes/Account/${objectId}`), {
				method: "PUT",
				headers: this.getHeaders(),
				body: JSON.stringify({
					...updateData,
					[ACCOUNT_FIELDS.UPDATED_AT]: {
						__type: "Date",
						iso: new Date().toISOString()
					}
				}),
			});

			const data = await this.handleResponse(response);

			return {
				success: true,
				data: {
					objectId: data.objectId,
					updatedAt: data.updatedAt,
				},
			};
		} catch (error) {
			console.error("更新用户信息失败:", error);
			return {
				success: false,
				error: this.getErrorMessage(error.message),
			};
		}
	}

	// 错误消息处理
	getErrorMessage(errorMessage) {
		if (errorMessage.includes("unique")) {
			return "用户名、邮箱或手机号已存在";
		} else if (errorMessage.includes("network") || errorMessage.includes("fetch")) {
			return "网络连接失败，请检查网络设置";
		} else if (errorMessage.includes("401")) {
			return "认证失败，请检查应用配置";
		} else if (errorMessage.includes("404")) {
			return "请求的资源不存在";
		} else {
			return "操作失败，请稍后重试";
		}
	}
}

// 创建单例实例
const leanCloudAPI = new LeanCloudAPI();

export default leanCloudAPI;
